package com.mjgy.controller;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.common.utils.R;
import com.mjgy.config.SysConfig;
import com.mjgy.service.PayService;
import com.mjgy.utils.Const;
import com.mjgy.utils.HttpRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Description: 支付接口
 * @author LGC
 * @date 2018年9月25日
 * @version V1.0
 */
@RestController
@RequestMapping("/pay")
public class PayController {

	@Autowired
	private PayService payService;

	/**
	 * @param request
	 * @param userId      支付人
	 * @param collecterId 收款人
	 * @param payMoney    支付金额
	 * @param type        支付类型（0=查看联系方式，1=红包图片，2=付费相册，3=发广播，4=购买会员）
	 * @param rechargeId  会员充值ID
	 * @param serviceId   购买的服务ID
	 * @return
	 */
	@RequestMapping("/getWxPayOrder")
	public R getWXPayOrder(HttpServletRequest request, Long userId, Long collecterId, double payMoney, int type, Long rechargeId, Long serviceId) {
		return payService.getWXPayOrder(request, userId, collecterId, payMoney, type, rechargeId, serviceId);
	}
	
	@RequestMapping("/wxPayNotify")
	public String wxPayNotify(HttpServletRequest request, HttpServletResponse response) {
		return payService.wxPayNotify(request, response);
	}
	
	@RequestMapping("/getAlipayOrder")
	public R getAlipayOrder(Long userId, double payMoney) {
		AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", SysConfig.alipayAppId, SysConfig.alipayMchKey, "json", "UTF-8", SysConfig.alipayPublicKey, "RSA2");
		AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
		AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
		model.setBody("充值会员");
		model.setSubject("悦夜APP支付");
		model.setOutTradeNo(Const.getOutTradeNo());
		model.setTimeoutExpress("30m");
		model.setTotalAmount(String.valueOf(payMoney));
		model.setProductCode("QUICK_MSECURITY_PAY");
		request.setBizModel(model);
		request.setNotifyUrl("http://47.106.82.187:8090/yueye/pay/alipayNotify");
		try {
			AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
			if(response.isSuccess()) {
				String result = HttpRequest.getURLDecoderString(response.getBody());
				return R.success().put("data", response.getBody());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return R.error();
	}
	
	@RequestMapping(value = "/alipayNotify", method = RequestMethod.POST)
	public String alipayNotify(HttpServletRequest request) {
		Map<String, String> params = new HashMap<>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
		    String name = (String) iter.next();
		    String[] values = (String[]) requestParams.get(name);
		    String valueStr = "";
		    for (int i = 0; i < values.length; i++) {
		        valueStr = (i == values.length - 1) ? valueStr + values[i]
		                    : valueStr + values[i] + ",";
		  	}
		    //乱码解决，这段代码在出现乱码时使用。
			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name, valueStr);
		}
		//切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
		//boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
		try {
			boolean flag = AlipaySignature.rsaCheckV1(params, SysConfig.alipayPublicKey, "UTF-8", "RSA2");
			if(flag) {
				return "success";
			}
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}
		return "failure";
	}
	
	//---------------------------------  管理后台接口  ----------------------------------------------//
	
	@RequestMapping("/payLogList")
	public R queryPayLogInfo(@RequestParam Map<String, Object> params) {
		return payService.payLogInfo(params);
	}
	
	@RequestMapping("/incomeList")
	public R queryIncomeInfo(@RequestParam Map<String, Object> params) {
		return payService.incomeInfo(params);
	}
}
